/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.xtd.facade;

import com.xtd.util.DateTimeUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Lu Yuanbin
 */
public abstract class AbstractFacade<T> {

    @PersistenceContext(unitName = "xtderp-ejbPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {


        return getEntityManager().createQuery("select e from " + entityClass.getSimpleName() + " as e").getResultList();
    }

//    public List<T> findRange(int[] range) {
//        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
//        cq.select(cq.from(entityClass));
//
//        javax.persistence.Query q = getEntityManager().createQuery(cq);
//        q.setMaxResults(range[1] - range[0]);
//        q.setFirstResult(range[0]);
//        return q.getResultList();
//
//    }
//
//    public int count() {
//        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
//
//        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
//        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
//        javax.persistence.Query q = getEntityManager().createQuery(cq);
//        return ((Long) q.getSingleResult()).intValue();
//    }
    public boolean checkUnique(Object entity, String fieldName, String fieldValue, boolean isNew) {
        long number = 0;
        if (fieldValue == null) {
            return false;
        }
        if (isNew) {
            number = (Long) getEntityManager().createQuery("select count(e) from " + entityClass.getSimpleName() + " as e where e." + fieldName + " = :fieldValue").setParameter("fieldValue", fieldValue).getSingleResult();
        } else {
            number = (Long) getEntityManager().createQuery("select count(e) from " + entityClass.getSimpleName() + " as e where e." + fieldName + " = :fieldValue and e <> :entity").setParameter("fieldValue", fieldValue).setParameter("entity", entity).getSingleResult();
        }
        if (number <= 0) {
            return true;
        } else {
            return false;
        }
    }

    public String generateNumber(String prefix, String formType) {
        String orderNumber = null;
        DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(new Date());
        String lastOrderNum = null;
        try {
            lastOrderNum = (String) getEntityManager().createQuery("select o.number from " + formType + " as o where o.id = (select MAX(o1.id) from ShootingOrder as o1 where o1.createdTime between :startDate and :endDate)").setParameter("startDate", DateTimeUtil.getTodayStart()).setParameter("endDate", DateTimeUtil.getTodayEnd()).getSingleResult();
        } catch (NoResultException e) {
        }
        String suffix = "001";
        if (lastOrderNum != null) {
            String lastOrder = lastOrderNum.substring(8);
            int num = Integer.valueOf(lastOrder);
            if (num < 10) {
                suffix = "00" + num;
            } else if (num < 100) {
                suffix = "0" + num;
            } else {
                suffix = String.valueOf(num);
            }
        }
        orderNumber = prefix + dateString + suffix;
        return orderNumber;
    }
}
